package com.example.audiobooks.user.man;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.audiobooks.MainActivity;
import com.example.audiobooks.R;

public class UserLoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);
    }
    public void reg(View view) {

        startActivity(new Intent(getApplicationContext(), RegisterActivity.class));

    }


    public void login(View view) {

        EditText EditTextname = (EditText) findViewById(R.id.name);
        EditText EditTextpassword = (EditText) findViewById(R.id.password);

        /*判断非空*/
        if (TextUtils.isEmpty(EditTextname.getText()) || TextUtils.isEmpty(EditTextpassword.getText())) {
            Toast.makeText(getApplicationContext(), "账户或密码为空，请重新输入", Toast.LENGTH_LONG).show();
        } else {
            new Thread() {
                @Override
                public void run() {

                    UserDao userDao = new UserDao();

                    boolean aa = userDao.login(EditTextname.getText().toString(), EditTextpassword.getText().toString());
                    int msg = 0;
                    if (aa) {
                        msg = 1;
                    }
                    hand1.sendEmptyMessage(msg);
                }
            }.start();
        }
    }

    final Handler hand1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_LONG).show();
//                    账号密码正确
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences.Editor editor = getSharedPreferences("data", 0).edit();
                        editor.putInt("join_key", 1);
                        editor.apply();
                    }
                }, 2000);
                //关闭当前页面
                finish();
                Intent intent = new Intent(UserLoginActivity.this, MainActivity.class);
                startActivity(intent);
                //登录成功，重新刷新主页
            } else {
                Toast.makeText(getApplicationContext(), "登录失败,账号或密码错误", Toast.LENGTH_LONG).show();
            }
        }
    };

}